package com.example.backendmanage.common.Interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.backendmanage.common.ReturnCode;
import com.example.backendmanage.common.exception.ServiceException;
import com.example.backendmanage.info.User;
import com.example.backendmanage.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(ReturnCode.CODE_401, "无token，请重新登录");
        }
        //得到userid
        String userId;
        try {
            userId= JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException jwt) {
            throw new ServiceException(ReturnCode.CODE_401,"token验证失败，检查token或重新登录");
        }
        User user= userMapper.findUserById(Integer.parseInt(userId));
        if (user == null) {
            throw new ServiceException(ReturnCode.CODE_600,"用户不存在，请重新登录");
        }
//        try {
//            System.out.println(user.getPassword());
//            // 用户密码加签验证 token
//            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//            jwtVerifier.verify(token); // 验证token
//        } catch (JWTVerificationException e) {
//            throw new ServiceException(ReturnCode.CODE_401, "token验证失败，请重新登录");
//        }
        return true;
    }
}
